<template>
  <div>
    <el-container>
      <el-main>
        <el-tabs type="border-card"
                 v-model="activeTable"
                 @tab-click="tabClick">
          <el-tab-pane label="报名进行中"
                       name="0"></el-tab-pane>
          <el-tab-pane label="报名未开始"
                       name="1"></el-tab-pane>
          <el-tab-pane label="报名已结束"
                       name="2"></el-tab-pane>
          <el-tab-pane label="我参与的"
                       name="3"></el-tab-pane>
          <el-empty v-if="pageInfo.data == ''"
                    description="您的小区暂无活动"></el-empty>
          <el-row>
            <el-col :span="24"
                    v-for="(activity,index) in pageInfo.data"
                    :key="activity.id">
              <!-- 活动信息概览 -->
              <el-card :body-style="{ padding: '10px'}"
                       shadow="hover">
                <!-- 轮播图 -->
                <template>
                  <el-carousel :interval="3000"
                               type="card"
                               height="250px">
                    <el-carousel-item v-for="photo in activity.photos"
                                      :key="photo">
                      <el-image style="width: 100%; height: 100%"
                                :src="photo"
                                fit="cover"></el-image>
                    </el-carousel-item>
                  </el-carousel>
                </template>
                <div style="padding: 14px;">
                  <span>{{activity.title}}</span>
                  <div class="bottom clearfix">
                    <el-col :span="17">
                      <!-- 点赞按钮 -->
                      <el-badge :value="activity.likes"
                                class="item"
                                type="warning">
                        <el-button type="warning"
                                   @click="like(activity,$event)"
                                   icon="el-icon-star-off"></el-button>
                      </el-badge>
                    </el-col>
                    <!-- 功能按钮 -->
                    <el-col :span="7">
                      <el-button type="info"
                                 id='`${activity.id}`'
                                 icon="el-icon-info"
                                 @click="infoClick(index)"
                                 circle></el-button>
                      <el-button type="info"
                                 icon="el-icon-user"
                                 @click="usersClick(activity.id,index)"
                                 circle></el-button>
                      <el-button type="primary"
                                 icon="el-icon-s-comment"
                                 @click="commentsClick(activity.id,index)"
                                 circle></el-button>
                      <el-button type="success"
                                 icon="el-icon-circle-plus"
                                 v-if="!activity.enrolled"
                                 @click="enroll(activity,index)"
                                 circle></el-button>
                      <el-button type="danger"
                                 icon="el-icon-check"
                                 v-else
                                 @click="enroll(activity,index)"
                                 circle></el-button>
                    </el-col>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tabs>
        <!-- 活动内容对话框 -->
        <el-dialog title=""
                   :visible.sync='infoVisible'>
          <el-descriptions class="margin-top"
                           :title="currentActivity.title"
                           :column="2"
                           direction="vertical"
                           border>
            <template slot="extra">
            </template>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-time"></i>
                报名开始时间
              </template>
              {{currentActivity.releaseTime}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-user"></i>
                报名人数
              </template>
              {{currentActivity.number}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-time"></i>
                报名截止时间
              </template>
              {{currentActivity.endTime}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-office-building"></i>
                活动小区
              </template>
              {{currentActivity.community.name}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-tickets"></i>
                活动内容
              </template>
              {{currentActivity.content}}
            </el-descriptions-item>

          </el-descriptions>
        </el-dialog>
        <!-- 报名信息对话框 -->
        <el-dialog title=""
                   :visible.sync='usersVisible'>
          <el-table :data="uPageInfo.data">
            <el-table-column type="index"
                             label="序号"></el-table-column>
            <el-table-column property="nickname"
                             label="昵称"></el-table-column>
            <el-table-column property="username"
                             label="用户名"></el-table-column>
          </el-table>
          <el-pagination @size-change="uPageSizeChange"
                         @current-change="uPageNumChange"
                         :current-page="uPageInfo.currentPage"
                         :page-sizes="[5, 10, 15, 20]"
                         :page-size="uPageInfo.size"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="uPageInfo.total">
          </el-pagination>
        </el-dialog>
        <!-- 评论区对话框 -->
        <el-dialog title=""
                   :visible.sync='commentsVisible'>
          <template>
            <el-table :data="cPageInfo.data">
              <el-table-column type="index"
                               label="序号"
                               align="center"></el-table-column>
              <el-table-column property="releaseTime"
                               label="发布时间"
                               width="100%"></el-table-column>
              <el-table-column property="user.username"
                               align="center"
                               label="发布用户"
                               width="100px"></el-table-column>
              <el-table-column property="content"
                               label="内容"></el-table-column>
              <el-table-column label="操作"
                               width="100%">
                <template slot-scope="scope">
                  <el-button type="danger"
                             icon="el-icon-delete"
                             v-if="user.id == scope.row.user.id"
                             @click="delComment(scope.$index,scope.row)"
                             circle></el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
          <el-row :gutter="0">
            <el-col :span="21">
              <el-pagination @size-change="cPageSizeChange"
                             @current-change="cPageNumChange"
                             :current-page="cPageInfo.currentPage"
                             :page-sizes="[5, 10, 15, 20]"
                             :page-size="cPageInfo.size"
                             layout="total, sizes, prev, pager, next, jumper"
                             :total="cPageInfo.total">
              </el-pagination>
            </el-col>
            <el-button type="primary"
                       icon="el-icon-edit"
                       @click="formVisible = true"
                       plain></el-button>
            <el-col :span="2">
            </el-col>
          </el-row>
        </el-dialog>
        <!-- 添加评论对话框 -->
        <el-dialog title=""
                   :visible.sync='formVisible'>
          <el-form ref="myComment"
                   :model="myComment"
                   label-width="80px">
            <el-form-item label="">
              <el-input type="textarea"
                        v-model="myComment.content"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="onComSubmit">发布评论</el-button>
              <el-button @click="formVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <!-- 添加活动对话框 -->
        <el-dialog title=""
                   :visible.sync='actFormVisible'>
          <el-form ref="myActivity"
                   :model="myActivity"
                   label-width="80px">
            <el-form-item label="活动名称">
              <el-input v-model="myActivity.title"></el-input>
            </el-form-item>
            <el-form-item label="活动小区">
              <el-select v-model="myActivity.cid"
                         placeholder="请选择活动小区">
                <el-option v-for="(community) in myCommunities"
                           :key="community.id"
                           :label="community.name"
                           :value="community.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="报名时间">
              <el-col :span="11">
                <el-date-picker :picker-options="pickerOptions"
                                type="datetime"
                                placeholder="选择开始时间"
                                v-model="myActivity.releaseTime"
                                style="width: 100%;"
                                value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
              </el-col>
              <el-col class="line"
                      :span="2">至</el-col>
              <el-col :span="11">
                <el-date-picker type="datetime"
                                :picker-options="pickerOptions"
                                placeholder="选择截止时间"
                                v-model="myActivity.endTime"
                                style="width: 100%;"
                                value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="活动图片">
              <el-upload :limit="9"
                         :multiple=true
                         class="upload-demo"
                         ref="upload"
                         action=""
                         :http-request="handleFile"
                         :auto-upload="false"
                         :file-list="fileList"
                         list-type="picture">
                <el-button slot="trigger"
                           size="small"
                           type="primary">选取文件</el-button>
                <div slot="tip"
                     class="el-upload__tip">只能上传jpg/png文件,且不超过5mb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="活动内容">
              <el-input type="textarea"
                        v-model="myActivity.content"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="uploadFile">立即发布</el-button>
              <el-button @click="actFormVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-row>
          <el-col :span="20">
            <el-pagination @size-change="pageSizeChange"
                           @current-change="pageNumChange"
                           :current-page="pageInfo.currentPage"
                           :page-sizes="[5, 10, 15, 20]"
                           :page-size="pageInfo.size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="pageInfo.total">
            </el-pagination>
          </el-col>
          <el-col :span="4">
            <el-button icon="el-icon-circle-plus"
                       type="primary"
                       @click="actFormVisible = true"
                       round>发布活动</el-button>
          </el-col>
        </el-row>
      </el-main>
    </el-container>

  </div>
</template>

<script>
export default {
  methods: {
    /* 文件上传 */
    uploadFile() {
      this.$refs.upload.submit()
      let formData = new FormData()
      for (let file of this.fileList) {
        formData.append('files', file)
      }
      this.$axios
        .post('oos/upload/img/activity', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        })
        .then((res) => {
          if (res.data.status == 'SUCCESS') {
            this.filePath = res.data.data.join()
            this.actSubmit()
          } else {
            this.$message.error(res.data.message)
          }
        })
    },
    handleFile(file) {
      this.fileList.push(file.file)
    },
    /* 发布活动 */
    actSubmit() {
      this.myActivity.photos = this.filePath
      console.log(this.myActivity.photos)
      this.myActivity.uid = this.user.id
      this.$axios.post('activity/add', this.myActivity).then((res) => {
        if (res.data.status == 'SUCCESS') {
          this.$message.success('活动发布成功!')
          this.filePath = ''
          this.actFormVisible = false
          this.fileList = []
          this.$axios.post('log/add', { target: '活动管理', type: '增加' })
        } else {
          this.$message.error(res.data.message)
          this.filePath = ''
          this.fileList = []
        }
      })
    },
    /* 报名 */
    enroll(activity, index) {
      if (!activity.enrolled) {
        this.$confirm('是否确认要报名该活动?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$axios
              .post('activity/entry/add/' + this.user.id + '/' + activity.id)
              .then((res) => {
                if (res.data.status == 'SUCCESS') {
                  // activity.likes++
                  // activity.likes--
                  activity.number++
                  activity.enrolled = true
                  this.$forceUpdate()
                  this.$message.success('报名成功')
                } else {
                  this.$message.error(res.data.message)
                }
              })
          })
          .catch(() => {
            return
          })
      } else {
        this.$message.error('请勿重复报名')
      }
    },
    /* 删除评论 */
    delComment(index, row) {
      this.$axios
        .delete('activity/comment/del/' + this.user.id + '/' + row.id)
        .then((res) => {
          if (res.data.status == 'SUCCESS') {
            this.cPageInfo.data.splice(index, 1)
            if (this.cPageInfo.currentPage != 1) {
              this.cPageInfo.currentPage--
            }
            this.getCPageInfo(this.currentActivity.id)
            this.$message.success('删除评论成功')
          } else {
            this.$message.error(res.data.message)
          }
        })
    },
    /* 获取报名表信息 */
    getUPageInfo(aid) {
      this.$axios
        .get(
          'activity/entry/find/' +
            aid +
            '/' +
            this.uPageInfo.currentPage +
            '/' +
            this.uPageInfo.size
        )
        .then((res) => {
          this.uPageInfo = res.data.data
        })
    },
    /* 获取评论信息 */
    getCPageInfo(aid) {
      this.$axios
        .get(
          'activity/comment/find/' +
            aid +
            '/' +
            this.cPageInfo.currentPage +
            '/' +
            this.cPageInfo.size
        )
        .then((res) => {
          this.cPageInfo = res.data.data
        })
    },
    /* 点赞方法 */
    like(activity, evt) {
      let target = evt.target
      while (target.nodeName !== 'BUTTON') {
        target = target.parentNode
      }
      target.blur()
      evt.target.blur()
      if (!activity.liked) {
        this.$axios
          .put('activity/like/' + activity.id + '/' + this.user.id)
          .then((res) => {
            if (res.data.status == 'SUCCESS') {
              activity.likes++
              activity.liked = true
              this.$message.success('点赞成功')
            } else {
              this.$message.error(res.data.message)
            }
          })
      } else {
        this.$axios
          .put('activity/dislike/' + activity.id + '/' + this.user.id)
          .then((res) => {
            if (res.data.status == 'SUCCESS') {
              activity.likes--
              activity.liked = false
              this.$message.success('取消点赞成功')
            } else {
              this.$message.error(res.data.message)
            }
          })
      }
    },
    /* 发布评论 */
    onComSubmit() {
      this.myComment.uid = this.user.id
      this.myComment.aid = this.currentActivity.id
      this.myComment.releaseTime = new Date().toLocaleString()
      this.$axios.post('/activity/comment/add', this.myComment).then((res) => {
        if (res.data.status == 'SUCCESS') {
          this.$message.success('评论发布成功')
          this.getCPageInfo(this.currentActivity.id)
          this.formVisible = false
        } else {
          this.$message.error(res.data.message)
        }
      })
      this.myComment.content
    },
    /* 显示评论 */
    commentsClick(aid, index) {
      this.currentActivity = this.pageInfo.data[index]
      this.getCPageInfo(aid)
      this.commentsVisible = true
    },
    /* 显示报名用户 */
    usersClick(aid, index) {
      this.currentActivity = this.pageInfo.data[index]
      this.getUPageInfo(aid)
      this.usersVisible = true
    },
    /* 显示活动详情 */
    infoClick(index) {
      this.currentActivity = this.pageInfo.data[index]
      this.infoVisible = true
    },
    /* 切换分类 */
    tabClick(tab, event) {
      this.pageInfo.currentPage = 1
      this.getPageInfo()
    },
    cPageNumChange(val) {
      this.cPageInfo.currentPage = val
      this.getCPageInfo(this.currentActivity.id)
    },
    cPageSizeChange(val) {
      this.cPageInfo.size = val
      this.getCPageInfo(this.currentActivity.id)
    },
    uPageNumChange(val) {
      this.uPageInfo.currentPage = val
      this.getUPageInfo(this.currentActivity.id)
    },
    uPageSizeChange(val) {
      this.uPageInfo.size = val
      this.getUPageInfo(this.currentActivity.id)
    },
    pageSizeChange(val) {
      // 页大小修改时
      // 得到当前页的大小
      this.pageInfo.size = val
      this.getPageInfo()
    },
    pageNumChange(val) {
      // 页码修改时
      this.pageInfo.currentPage = val
      this.getPageInfo()
    },
    /* 获取页面信息 */
    getPageInfo() {
      if (this.user == null) {
        this.user = JSON.parse(sessionStorage.getItem('user'))
      }
      /* 获取动态信息刚加载默认查询所有、第一页、5个 */
      this.$axios
        .get(
          'activity/find/' +
            this.activeTable +
            '/' +
            this.pageInfo.currentPage +
            '/' +
            this.pageInfo.size
        )
        .then((res) => {
          if (res.data.status == 'SUCCESS') {
            //保存数据
            this.pageInfo = res.data.data
            this.pageInfo.data.forEach((activity) => {
              if (activity.photos != null) {
                activity.photos = activity.photos.split(',')
              }
              this.aids.push(activity.id)
            })
            this.$axios.post('activity/like/find', this.aids).then((res) => {
              this.pageInfo.data.forEach((activity) => {
                if (res.data.data.includes(activity.id)) {
                  activity.liked = true
                  return
                }
                activity.liked = false
              })
            })
            this.$axios.post('activity/entry/find', this.aids).then((res) => {
              this.pageInfo.data.forEach((activity) => {
                if (res.data.data.includes(activity.id)) {
                  activity.enrolled = true
                  return
                }
                activity.enrolled = false
              })
              this.$forceUpdate()
            })
            this.$axios.get('community/findByUid').then((res) => {
              if (res.data.status == 'SUCCESS') {
                this.myCommunities = res.data.data
              } else {
                this.$message.error(res.data.message)
              }
            })
          } else {
            this.$message.error('页面初始化失败')
          }
        })
    },
  },
  data() {
    return {
      filePath: '',
      fileList: [],
      myCommunities: {},
      actFormVisible: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        },
      },
      myActivity: {},
      myComment: {
        content: '',
      },
      currentActivity: {
        community: {
          name: '',
        },
      },
      formVisible: false,
      commentsVisible: false,
      usersVisible: false,
      infoVisible: false,
      cPageInfo: {
        currentPage: 1,
        size: 5,
        total: 0,
        totalPage: 1,
        data: [],
      },

      uPageInfo: {
        currentPage: 1,
        size: 5,
        total: 0,
        totalPage: 1,
        data: [],
      },
      pageInfo: {
        currentPage: 1,
        size: 5,
        total: 0,
        totalPage: 1,
        data: '',
      },
      activeTable: '0',
      user: null,
      aids: [],
    }
  },
  mounted() {
    this.getPageInfo()
  },
}
</script>

<style scoped>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}
</style>
